package com.roadjava.like.controller;

import com.roadjava.like.bean.entity.LikedDO;
import com.roadjava.like.bean.entity.LikedEQ;
import com.roadjava.like.bean.res.Result;
import com.roadjava.like.config.HoneyLogs;
import com.roadjava.like.enums.LogEnum;
import com.roadjava.like.security.RateLimitService;
import com.roadjava.like.service.LikedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/likes")
public class LikedController {

    @Autowired
    private LikedService likedService;

    // 引入 RateLimitService
    private final RateLimitService rateLimitService = new RateLimitService();

    // 添加点赞
    @HoneyLogs(operation = "添加点赞记录",type = LogEnum.ADD)
    @PostMapping
    public Result<LikedEQ> addLike(@RequestBody LikedEQ liked) {


        likedService.addLike(liked);
        // 通过Service层添加点赞
        return Result.buildSuccess(liked);
        // 返回创建的点赞对象
    }

    @HoneyLogs(operation = "点赞记录",type = LogEnum.DELETE)
    // 删除点赞
    @DeleteMapping
    public Result<Void> removeLike(@RequestParam Long resourceId, @RequestParam Long Id) {
        String userIdStr = Id.toString();
        // 假设通过 userId 获取用户 ID
        if (!rateLimitService.isAllowed(userIdStr)) {
            return Result.buildFailure("Too many requests");
            // 返回429 Too Many Requests状态码
        }

        likedService.removeLike(resourceId, Id);
        // 通过Service层删除点赞，使用资源ID和用户ID
        return Result.buildSuccess();
        // 返回200 OK状态，表示删除成功
    }

    // 查询用户的所有点赞

    @GetMapping("/{userId}")
    public Result<List<LikedDO>> getUserLikes(@PathVariable Long userId) {
        List<LikedDO> likes = likedService.getUserLikes(userId);
        // 通过Service层查询用户所有点赞
        return Result.buildSuccess(likes);
        // 返回点赞列表
    }

    // 查看某个资源的点赞总数
    @GetMapping("/count/{resourceId}")
    public Result<Long> getLikeCount(@PathVariable Long resourceId) {
        Long count = likedService.getLikeCount(resourceId);
        // 通过Service层查询点赞总数
        return Result.buildSuccess(count);
        // 返回点赞总数
    }

    // 检查用户是否点赞
    @GetMapping("/check")
    public Result<Boolean> checkUserLiked(@RequestParam Long userId, @RequestParam Long resourceId) {
        boolean liked = likedService.checkUserLiked(userId, resourceId);
        // 通过Service层检查用户是否点赞
        return Result.buildSuccess(liked);
        // 返回是否点赞的结果
    }
}
